import Taro, { Component } from '@tarojs/taro'
import { View, Button, Form, Input } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'
import Base from '@/components/Base'
import { ToastUtil } from '@/utils/toastUtil'
import { MessageBoxUtil } from '@/utils/messageBoxUtil'
import { setToken } from '@/utils/request/auth'
import { login } from '@/utils/api';

import './index.scss'

@inject('toastStore')
@observer
class Index extends Component {
  config = {
    navigationBarTitleText: '用户信息'
  }

  constructor(props) {
    super(props)
    this.state = {
      username: 'admin',
      password: 'admin'
    }
  }

  handleChange(key, e) {
    this.setState({
      [key]: e.detail.value
    })
  }

  login() {
    const { username, password } = this.state
    // const res = await request.post('/user/login', { username, password })
    login({ username, password })
      .then(res => {
        console.log('res', res)
        ToastUtil.success('登录成功')
        setToken(res.data.token)
        this.toSettingPage()
      })
      .catch(err => {
        ToastUtil.fail(err + '')
        console.log(err)
      })
  }

  showToast(type = 'info', msg = '') {
    ToastUtil[type](msg)
  }

  hideToast() {
    ToastUtil.hide()
  }

  toSetPage() {
    Taro.navigateTo({
      url: '/pages/set/index'
    })
  }

  showMessageBox() {
    const option = {
      title: '标题123',
      content: '内容123'
    }

    MessageBoxUtil.confirm(
      option,
      () => {
        console.log('confirm')
        console.log(this.state)
      },
      () => {
        console.log('cancel')
      }
    )
  }

  render() {
    const { username, password } = this.state

    return (
      <Base>
        <View className="index">
          <Form onSubmit={this.formSubmit} onReset={this.formReset}>
            <Input
              type="text"
              placeholder="将会获取焦点"
              value={username}
              onInput={this.handleChange.bind(this, 'username')}
            />
            <Input
              type="text"
              placeholder="将会获取焦点"
              value={password}
              onInput={this.handleChange.bind(this, 'password')}
            />
            <Button onClick={this.login}>登录</Button>
            <Button onClick={this.showToast.bind(this, 'success', '成功提示')}>
              显示成功提示
            </Button>
            <Button onClick={this.showToast.bind(this, 'info', '信息提示')}>
              显示信息提示
            </Button>
            <Button onClick={this.showToast.bind(this, 'warning', '警告提示')}>
              显示警告提示
            </Button>
            <Button onClick={this.showToast.bind(this, 'fail', '失败提示')}>
              显示失败提示
            </Button>
            <Button onClick={this.hideToast}>隐藏toast</Button>
            <Button onClick={this.toSetPage}>跳转</Button>
            <Button onClick={this.showMessageBox}>显示消息对话框</Button>
          </Form>
        </View>
      </Base>
    )
  }
}

export default Index
